package com.itheima.controller;

import com.itheima.domain.Permission;
import com.itheima.domain.Role;
import com.itheima.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.security.RolesAllowed;
import java.util.List;

/**
 * ClassName:RoleController
 * Package:com.itheima.controller
 * Description:
 * Date:2020/3/12 15:07
 * User: snow
 */
@Controller
@RequestMapping("/role")
//ADMIN身份用户可以访问
@RolesAllowed("ADMIN")
public class RoleController {

	@Autowired
	private RoleService roleService;

	@RequestMapping("/findAll.do")
	public ModelAndView findAll() throws Exception{
		ModelAndView view = new ModelAndView();
		List<Role> roleList = roleService.findAll();
		view.addObject("roleList",roleList);
		view.setViewName("role-list");
		return view;
	}

	@RequestMapping("/save.do")
	public String save(Role role) throws Exception{
		roleService.save(role);
		return "redirect:findAll.do";
	}

	@RequestMapping("/findById.do")
	public ModelAndView findById(String id) throws  Exception{
		ModelAndView view = new ModelAndView();
		Role role = roleService.findById(id);
		view.addObject("role",role);
		view.setViewName("role-show");
		return view;
	}

	/**
	 * 查找角色可添加权限
	 * @param roleId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/findRoleByIdAndAllPermission.do")
	public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id" ,required = true)
			String roleId) throws Exception{
		// 根据id查询role
		Role role = roleService.findById(roleId);
		// 根据id查询可添加权限
		List<Permission> permissionList = roleService.findOtherPermission(roleId);
		ModelAndView view = new ModelAndView();
		view.addObject("role",role);
		view.addObject("permissionList",permissionList);
		view.setViewName("role-permission-add");
		return view;
	}

	@RequestMapping("/addPermissionToRole.do")
	public String addPermissionToRole
			(@RequestParam(name = "roleId",required = true) String roleId,
			 @RequestParam(name = "ids",required = true) String[] permissionIds) throws  Exception{
		roleService.addPermissionToRole(roleId,permissionIds);
		return "redirect:findAll.do";
	}

}
